document.addEventListener("DOMContentLoaded", function () {
    const page = window.location.pathname.split("/").pop();

    if (page === 'warehouse.html') {
        loadWarehouses();
    } else if (page === 'item.html') {
        const urlParams = new URLSearchParams(window.location.search);
        const warehouseId = urlParams.get('warehouseId');
        if (warehouseId) {
            loadItems(warehouseId);
        }
    } else if (page === 'history.html') {
        loadOrders();
    }
});

function loadWarehouses() {
    fetch('/api/warehouses')
        .then(response => response.json())
        .then(data => {

            const tbody = document.querySelector('tbody');
            tbody.innerHTML = '';
            data.forEach(warehouse => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${warehouse.warehouseId}</td>
                    <td>${warehouse.warehouseName}</td>
                    <td>${warehouse.warehouseType}</td>
                    <td>${warehouse.inventoryAmount}</td>
                    <td><a href="item.html?warehouseId=${warehouse.warehouseId}">详情</a></td>
                `;
                tbody.appendChild(tr);
            });
        });
}

function loadItems(warehouseId) {
    fetch(`/api/warehouses/${warehouseId}/items`)
        .then(response => response.json())
        .then(data => {
            var title = document.querySelector("#title");
            title.innerHTML = "仓库ID:" + warehouseId + "的物品列表"
            const tbody = document.querySelector('tbody');
            tbody.innerHTML = '';
            data.forEach(item => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${item.itemId}</td>
                    <td>${item.itemName}</td>
                    <td>${item.unitOfMeasure}</td>
                    <td>${item.quantity}</td>
                    <td>${item.plannedUnitPrice}</td>
                `;
                tbody.appendChild(tr);
            });
        });
}

function loadOrders() {
    fetch('/api/orders')
        .then(response => response.json())
        .then(data => {
            const tbody = document.querySelector('tbody');
            tbody.innerHTML = '';
            data.forEach(order => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${order.id}</td>
                    <td>${order.date}</td>
                    <td>${order.warehouseId}</td>
                    <td>${order.warehouseName}</td>
                    <td>${order.itemId}</td>
                    <td>${order.itemName}</td>
                    <td>${order.quantity}</td>
                    <td>${order.plannedUnitPrice}</td>
                `;
                tbody.appendChild(tr);
            });
        });
}